package xdu.lz.protocol.socekt;

import xdu.lz.framework.RequestWrap;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @date 2020/5/15 23:00
 */
class MyTask implements Callable {


    private RequestWrap requestWrap;

    public MyTask(RequestWrap requestWrap) {
        this.requestWrap = requestWrap;
    }

    @Override
    public Object call() throws Exception {
        System.out.println("【socekt server get requestWrap from server】 " + requestWrap);
        System.out.println("被线程池执行call方法");
        Thread.sleep(1000);
        return " ======= socekt server res =======";
    }
}

public class SocketServer {

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    ServerSocket serverSocket;
    ObjectInputStream input;
    ObjectOutput output;
    Socket socket;

    public void export(String hostName, int port) {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            while (true) {
                Socket socket = serverSocket.accept();
                input = new ObjectInputStream(socket.getInputStream());
                RequestWrap requestWrap = (RequestWrap) input.readObject();
                //丢入线程池处理
                Future future = executorService.submit(new MyTask(requestWrap));
                String res = (String) future.get();
                System.out.println("【socekt server return res】 " + res);
                output = new ObjectOutputStream(socket.getOutputStream());
                output.writeObject(res);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
